import { observable, flow, action, configure } from 'mobx';
import _ from 'lodash';
import { Actions } from 'react-native-router-flux';
import { Alert } from 'react-native';
import * as wechat from 'react-native-wechat';
import { setToken } from '../../utils/request';
import {
  sendSMS,
  loginMobile,
  logout,
  getPosts,
  updateUserInfo,
  getApplyStatus,
  getMe,
  bindMobile,
  bindWechat,
  loginWechat,
  getWeChatToken,
  getWeChatUserInfo,
  getSmsTemplate,
  updateSmsTemplate
} from '../services/user';
import customers from "../../modules/customer/models/customers";

configure({ enforceActions: true });

class User {
  @observable userInfo = {};
  @observable posts = [];
  @observable pending = false;
  @observable submitStatus = false;
  @observable institutionStatus = false;
  @observable institutionId = '';
  @observable smsTemplate = '';
  @observable applyStatus = {};
  @observable sendError = null;
  @observable wechatIsInstall = false;

  @action
  saveUserInfo = userInfo => {
    if (userInfo) {
      const { accessToken } = userInfo;
      storage.save({
        key: 'userInfo',
        data: userInfo
      });
      global.token = accessToken;
      this.userInfo = userInfo;
      this.syncSms();
      Actions.reset('main');
    } else {
      global.token = null;
      this.clearStorage();
      this.userInfo = {};
      this.reset();
      customers.reset();
      Actions.reset('start');
    }
    setToken(() => global.token);
    this.pending = false;
  };
  @action
  setPending = bool => {
    this.pending = bool;
  };
  @action
  submit = stop => {
    if (stop) {
      this.submitStatus = false;
      return;
    }
    this.submitStatus = true;
  };
  checkWechat = flow(function*(){
    const isInstalled = yield wechat.isWXAppInstalled();
    if (isInstalled) {
      this.wechatIsInstall = true;
    }
  });
  wxAuth = flow(function* (e, bind) {
    const isInstalled = yield wechat.isWXAppInstalled();
    if (isInstalled) {
      yield this.setPending(true);
      try {
        const { code } = yield wechat.sendAuthRequest(
          'snsapi_userinfo',
          'dacheng_rnt'
        );
        const { access_token, openid } = yield getWeChatToken(code);
        const {
          openid: weChatOpenId,
          headimgurl: weChatHeadImgUrl,
          nickname: weChatNickname,
          sex: weChatSex
        } = yield getWeChatUserInfo(access_token, openid);
        if (!bind) {
          const data = yield loginWechat({
            weChatOpenId,
            weChatHeadImgUrl,
            weChatNickname,
            weChatSex
          });
          yield this.saveUserInfo(data);
        } else {
          const data = yield bindWechat({
            weChatOpenId,
            weChatHeadImgUrl,
            weChatNickname,
            weChatSex
          });
          yield this.getMe(true);
        }
      } catch (e) { }
    } else {
      Alert.alert('没有安装微信', '请先安装微信客户端在进行授权登录', [
        { text: '知道了' }
      ]);
    }
  });
  @action
  setSendError = value => {
    this.sendError = value;
  };
  sendSmsCode = flow(function* (mobile, action = 1) {
    const res = yield sendSMS(mobile, action);
    if (!res) {
      this.setSendError(true);
    }
  });
  storeSms = data => {
    storage.save({ key: 'smsTemplate', data });
  };
  syncSms = flow(function* (force) {
    if (force) {
      yield this.fetchSms();
    } else {
      try {
        const data = yield storage.load({ key: 'smsTemplate' });
        this.smsTemplate = data;
      } catch (e) {
        yield this.fetchSms();
      }
    }
  });
  fetchSms = flow(function* () {
    const smsTemplate = yield getSmsTemplate();
    yield this.storeSms(smsTemplate);
    this.smsTemplate = smsTemplate;
  });
  updateSms = flow(function* (content) {
    try {
      yield updateSmsTemplate(content);
      this.storeSms(content);
      this.smsTemplate = content;
    } catch (e) { }
  });
  login = flow(function* (values) {
    const userInfo = yield loginMobile(values);
    if (userInfo) {
      yield this.saveUserInfo(userInfo);
    }
  });
  bindMobile = flow(function* (values) {
    const { success } = yield bindMobile(values);
    if (success) {
      yield this.getMe(true);
    }
  });
  getMe = flow(function* (force) {
    if (this.userInfo.insuranceOrgId && !force) {
      return this.userInfo;
    }
    const userInfo = yield getMe();
    const oldUserInfo = yield storage.load({ key: 'userInfo' });
    const newUserInfo = { ...oldUserInfo, ...userInfo, isNew: true };
    storage.save({
      key: 'userInfo',
      data: newUserInfo
    });
    this.userInfo = newUserInfo;
    return newUserInfo;
  });
  logout = flow(function* () {
    yield logout();
    yield this.saveUserInfo();
  });
  setInstitutionId = flow(function* (id) {
    let posts;
    try {
      this.pending = true;
      posts = yield getPosts(id);
      this.pending = false;
      this.submitStatus = false;
      if (posts && posts.length > 0) {
        // _.forEach(posts, ({ insuranceOrgPostId, name }) => {
        //   _p[insuranceOrgPostId] = name;
        // });
        this.posts = _.map(posts, ({ insuranceOrgPostId: value, name: label }) => ({
          value,
          label
        }));
        this.institutionId = id;
        this.pending = false;
        this.submitStatus = false;
        return id;
      }
    } finally {
      this.pending = false;
      this.submitStatus = false;
    }
  });
  init = flow(function* () {
    this.syncSms();
    yield this.checkApplyStatus();
  });
  checkApplyStatus = flow(function* () {
    const status = yield getApplyStatus();
    if (status) {
      this.applyStatus = status;
    }
  });
  update = flow(function* (values, callback) {
    const data = yield updateUserInfo({
      ...values,
      mobile: this.userInfo.mobile
    });
    if (data) {
      if (_.isFunction(callback)) {
        callback();
      }
      yield this.getMe(true);
    }
  });
  @action
  reset = () => {
    this.userInfo = {};
    this.posts = [];
    this.pending = false;
    this.submitStatus = false;
    this.institutionStatus = false;
    this.institutionId = '';
    this.smsTemplate = '';
    this.applyStatus = {};
    this.sendError = null;
  };
  clearStorage = () => {
    storage.clearMapForKey('customers');
    storage.remove({ key: 'smsTemplate' });
    storage.remove({ key: 'userInfo' });
  };
}
export default new User();
